package wsp.dailymarket.auth;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;

/**
 * Authentication class
 * This is not a bean. Beans are stupidly pointless for security.
 * @author Matt
 */
public class Authentication {

	private String user;
	private int clientType;
	private int status;
	private String statusMessage;

	protected Authentication(String user, int status, String statusMessage, int clientType) {
		this.user = user;
		this.status = status;
		this.statusMessage = statusMessage;
		this.clientType = clientType;
	}

	public boolean isAuthorized() {
		return status == 0;
	}

	/**
	 * Status of authorization
	 * @return Status code:
	 *				0  = Authorized
	 *				-1 = Invalid or Bad ClientType
	 *				1  = Bad Username or Password
	 *				2  = Database Error
	 *				3  = Create user failed: user id (email) missing or invalid
	 *				4  = Create user failed: password missing or invalid
	 *				5  = Create user failed: user id (email) exists in database
	 */
	public int getStatus() {
		return this.status;
	}

	public String getStatusMessage() {
		return this.statusMessage;
	}

	public String getUserID() {
		return this.user;
	}

	public int getClientType() {
		return this.clientType;
	}

	/**
	 * Get an authorization object
	 * @param username User ID (email) of client
	 * @param password Client password
	 * @return Authentication object
	 */
	public static Authentication getAuthorization(DataSource ds, String username, String password) {

		// Pull data from database
		Connection conn = null;
		try {
			try {
				conn = ds.getConnection();
				Statement stmt = conn.createStatement();
				String sql = "SELECT * FROM app.clients WHERE client_id = '" + username + "' AND password = '" + password + "'";
				ResultSet rs = stmt.executeQuery(sql);
				if (rs.next()) {
					return new Authentication(username, 0, "Authenticated", rs.getInt("client_type"));
				} else {
					return new Authentication(username, 1, "User ID or password invalid.", 0);
				}
			} finally {
				if (conn != null) conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace(System.err);
			return new Authentication(username, 2, "Database Error", 0);
		}
	}

	/**
	 * Create an empty authentication object
	 * @return Empty, invalid authentication object
	 */
	public static Authentication createEmpty() {
		return new Authentication("", -1, "Invalid", 0);
	}

}
